package com.example.authority.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;

@Component
@ConfigurationProperties(prefix = "aliyun.sms")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SmsUtil {

    private String signName;
    private String templateCode;
    private String accessKeyId;
    private String accessKeySecret;

    public void sendSmsCode(String phone, String code) throws Exception {
        if(signName==null||signName.equals("")){throw new Exception("短信配置错误");}
        StaticCredentialProvider provider =
                StaticCredentialProvider.create(Credential.builder()
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                                .setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // 注意：短信验证码只支持4-6位纯数字！！！
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName) // 签名名称
                .templateCode(templateCode) // 模版CODE
                .phoneNumbers(phone) // 要发送短信给哪一个手机号
                .templateParam("{\"code\":\"" + code + "\"}")
                .build();

        CompletableFuture<SendSmsResponse> response =
                client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));

        client.close();
    }
}

